package com.zj.auth.apis;

import com.zj.auth.SendPhoneCode;
import com.zj.auth.anno.IgnoreAuth;
import com.zj.auth.bean.LoginTo;
import com.zj.auth.bean.LoginToken;
import com.zj.auth.bean.ThirdLoginTo;
import com.zj.auth.cache.RedisUtil;
import com.zj.auth.service.LoginAuth;
import com.zj.auth.service.LoginAuthFactory;
import com.zj.auth.type.LoginType;
import com.zj.auth.util.CodeUtil;
import cn.zj.smart.util.exception.ServiceException;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

/**
 * 登陆相关api
 *
 * @author xi.yang
 * @create 2020-11-19 18:49
 **/
@RestController
public class LoginApi {
    @Autowired
    private LoginAuthFactory loginAuthFactory;
    @Autowired
    private SendPhoneCode sendPhoneCode;
    @Autowired
    private RedisUtil redisUtil;

    /**
     * @param loginTo
     */
    @ApiOperation("获取验证码")
    @PostMapping("code")
    @IgnoreAuth
    public void sendCode(@RequestBody LoginTo loginTo) {
        String code = CodeUtil.randomCode();
        LoginType loginType = loginTo.getLoginType();
        String phoneNum = loginTo.getAccount();
        if (LoginType.PHONE.equals(loginType)) {
            boolean sendResult = sendPhoneCode.sendCode(phoneNum, code);
            if (!sendResult) {
                throw new ServiceException("send code error");
            }
            redisUtil.cachePhoneCode(phoneNum, code);
        }
    }

    @ApiOperation("常规登陆")
    @PostMapping("login")
    @IgnoreAuth
    public LoginToken login(@RequestBody LoginTo loginTo) {
        LoginAuth loginAuth = loginAuthFactory.getCommonLoginAuth(loginTo.getLoginType());
        return loginAuth.login(loginTo);
    }

    @ApiOperation("第三方登陆")
    @PostMapping("thirdLogin")
    @IgnoreAuth
    public LoginToken thirdLogin(@RequestBody ThirdLoginTo thirdLoginTo) {
        LoginAuth loginAuth = loginAuthFactory.getThirdLoginAuth(thirdLoginTo.getLoginType());
        return loginAuth.login(thirdLoginTo);
    }
}
